import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createHtmlPlugin } from 'vite-plugin-html'

// 使用@进行路径别名时
import { fileURLToPath } from 'node:url'

export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_TITLE, VITE_APP_BASE_PATH, VITE_APP_BASE_URI } = env
  let target = ''
  if (mode === 'development') {
    target = 'http://127.0.0.1:8089/api'
  } else {
    target = 'https://www.xxx.com/api'
  }
  return {
    base: VITE_APP_BASE_PATH, // 打包路径
    build: {
      outDir: 'admin',
      assetsDir: 'static',
    },
    // 解决使用@符号报错问题
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      createHtmlPlugin({
        inject:{
          data:{
            // 定义了一个title 变量，可以被html中进行引用
            title: VITE_APP_TITLE,
          }
        }
      })
    ],
    server: {
      host: '0.0.0.0',
      open: true,
      proxy: {
        [VITE_APP_BASE_URI]: {
          target, // 后端接口地址
          changeOrigin: true,
          ws: true,
          rewrite: (path) => {
            return path.replace(new RegExp(`^${VITE_APP_BASE_URI}`), '')
          }
        }
      }
    }
  }
})
